from odoo import api, fields, models, Command, _
from odoo.tools import float_compare
from odoo.exceptions import ValidationError, UserError


class MrpProductionSplit(models.TransientModel):
    _inherit = 'mrp.production.split'

    remain_qty = fields.Integer(string='Remain Qty')
    panel_qty = fields.Integer(string='Qty(PANEL)')
    value_pnl = fields.Float(string='PCS/PANEL', digits='Product Unit of Measure')
    value_set = fields.Float(string='PCS/SET', digits='Product Unit of Measure')

    @api.onchange('production_detailed_vals_ids')
    def onchange_remain_qty(self):
        split_qty = sum(self.production_detailed_vals_ids.mapped('panel_qty'))
        self.remain_qty = self.panel_qty - split_qty

    def action_split(self):
        if self._context.get('new_split'):
            return self.action_split2()
        else:
            return super().action_split()

    def action_split2(self):
        # 外层+内层订单汇总
        # children_ids = self._get_children_ids()
        # productions = None
        # children_ids = [self.production_id]
        # for production_id in children_ids:
            # if production_id not in ['confirmed', 'progress']: continue
        production_id = self.production_id
        detailed_vals = self._auto_split(production_id)
        if production_id.state in ('confirmed', 'progress'):
            productions = production_id._split_productions_progress({production_id: detailed_vals})
            productions = productions.filtered(lambda x: x.state != 'cancel')
            tree_id = self.env.ref('mrp.mrp_production_tree_view').id
            form_id = self.env.ref('mrp.mrp_production_form_view').id
            return {
                'name': 'Rework',
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'form, tree',
                'res_model': 'mrp.production',
                'domain': [('id', 'in', productions.ids)],
                'views': [(tree_id, 'tree'), (form_id, 'form')],
                'context': {'create': 0},
            }
        else:
            raise UserError(_('The current status does not allow splitting orders'))

    def _get_children_ids(self):
        children_ids = [self.production_id]  # 全部内层MO
        visited = [self.production_id]
        production_id = visited[0]
        while visited and visited.pop(0):
            children_ids.extend([p for p in production_id._get_children()])
            visited.extend([p for p in production_id._get_children()])
            if visited:
                production_id = visited[0]
        return children_ids

    def _auto_split(self, production_id):
        """
        production_id: 内层MO object
        根据顶层拆分MO数量比例，对内层进行逐一拆分
        """

        product_qty = sum([detail.quantity for detail in self.production_detailed_vals_ids])
        # numerator = [detail.quantity for detail in self.production_detailed_vals_ids]
        # denominator = self.counter
        if production_id == self.production_id:
            # counter=6,  拆分:[1,2,3]
            detailed_vals = [detail.quantity for detail in self.production_detailed_vals_ids]
        else:
            # 根据主MO，拆分的比例，自动拆分内层MO,
            # 内层物料数量：10， detailed_vals = [10*1/6, 10*2/6, 10*3/6]
            detailed_vals = [production_id.product_qty * detail.quantity / product_qty for detail in
                             self.production_detailed_vals_ids]
        if float_compare(sum(detailed_vals), production_id.product_qty, 2):
            # 拆分后数量与原MO订单数量不一致{}
            raise ValidationError('The quantity after the split is inconsistent with the quantity of the original MO order{}'.format(production_id.name))
        return detailed_vals


class MrpProductionSplitLine(models.TransientModel):
    _inherit = 'mrp.production.split.line'

    panel_qty = fields.Integer(string='Qty(PANEL)')
    user_id = fields.Many2one(
        'res.users', 'Responsible', default= lambda self: self.env.uid,
        domain=lambda self: [('groups_id', 'in', self.env.ref('mrp.group_mrp_user').id)])
    date = fields.Datetime('Schedule Date', default=fields.Datetime.now())

    @api.onchange('panel_qty')
    def onchange_quantity(self):
        if self.panel_qty:
            self.quantity = self.panel_qty * self.mrp_production_split_id.value_pnl


